// import * as Cesium from 'cesium'
// import "cesium/Build/Cesium/Widgets/widgets.css";

Cesium.Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwMmY0MjAxNS05ZWM5LTQ3YTMtYjRlZS1iODg5MTJjNDEwYTAiLCJpZCI6MTIzMDA1LCJpYXQiOjE2NzUyMzU5Njd9.hOoDLtU6Lv05cIhmdID6BHwBTD4db1DJqMkth1uW444";

// Cesium.Camera.DEFAULT_VIEW_FACTOR = 0 //摄像机视口远近参数，可设置地球大小,大于零会使它远离范围，而小于零会使它接近范围
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
  90,
  -20,
  110,
  90
); //设置默认显示中国正上方

const TDTTK = "cb37cf59d50b321428b932316ab09fcc";
// 当前方法内所有的
let interval = null;

let viewer;
export function initCesiumMap(target) {
  // const Cartesian = Cesium.Cartesian3.fromDegrees(0, 0, 500.0)
  viewer = new Cesium.Viewer(target, {
    animation: false, // 是否显示动画控件
    shouldAnimate: false, // 是否初始时刻运动
    homeButton: false, // 是否显示Home按钮
    fullscreenButton: false, // 是否显示全屏按钮
    baseLayerPicker: false, // 是否显示图层选择控件 去掉自带的图层选择器
    geocoder: false, // 是否显示地名查找控件,设置为true，则无法查询
    timeline: false, // 是否显示时间线控件
    sceneModePicker: false, // 是否显示投影方式控件 三维/二维
    navigationHelpButton: false, // 是否显示帮助信息控件
    infoBox: false, // 是否显示点击要素之后显示的信息 信息框小部件
    baseLayerPicker: false, // 不显示底图选择器，如果你只想用默认底图的话
    requestRenderMode: false, // true启用请求渲染模式:更新实体需拖动地图 视图才更新[true 加载完entity后requestRender一下]
    scene3DOnly: false, // 每个几何实例将只能以3D渲染以节省GPU内存 如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
    sceneMode: 3, // 初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
    scene3DOnly: true, // 仅显示3D场景
    fullscreenElement: document.body, // 全屏时渲染的HTML元素
    selectionIndicator: false, // 是否显示选取指示器组件
  });
  viewer._cesiumWidget._creditContainer.style.display = "none"; // 隐藏版权信息
  const imageLayers = viewer.scene.imageryLayers;
  imageLayers.remove(imageLayers.get(0)); //移除默认影像图层

  // 设置中心点为特定的经纬度（例如：经度116.38，纬度39.9）
  // viewer.camera.setView({
  //     destination: Cesium.Rectangle.fromDegrees(90, -20, 110, 90)
  // });

  /*
   * 天地图
   */
  // // 天地图影像
  // const tdtLayer = new Cesium.WebMapTileServiceImageryProvider({
  //   url: `http://t0.tianditu.com/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&tk=${TDTTK}`,
  //   layer: "tdt",
  //   style: "default",
  //   format: "image/jpeg",
  //   tileMatrixSetID: "w",
  //   maximumLevel: 18,
  //   show: false,
  // });
  // viewer.imageryLayers.addImageryProvider(tdtLayer);
  // // 天地图注记
  // const tdtAnnotionLayer = new Cesium.WebMapTileServiceImageryProvider({
  //   url: `http://t0.tianditu.com/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&tk=${TDTTK}`,
  //   layer: "tdtAnno",
  //   style: "default",
  //   format: "image/jpeg",
  //   tileMatrixSetID: "w",
  //   maximumLevel: 18,
  //   show: false,
  // });
  // viewer.imageryLayers.addImageryProvider(tdtAnnotionLayer);

  /*
   * 高德地图
   */
  //高德矢量图
  // let tdtLayer1 = new Cesium.UrlTemplateImageryProvider({
  // 	url: "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
  // 	minimumLevel: 3,
  // 	maximumLevel: 18
  // })
  // viewer.imageryLayers.addImageryProvider(tdtLayer1)
  //高德影像
  let tdtLayer2 = new Cesium.UrlTemplateImageryProvider({
    url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
    minimumLevel: 3,
    maximumLevel: 18,
  });
  viewer.imageryLayers.addImageryProvider(tdtLayer2);
  //高德路网中文注记
  let tdtLayer = new Cesium.UrlTemplateImageryProvider({
    url: "http://webst02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8",
    minimumLevel: 3,
    maximumLevel: 18,
  });
  viewer.imageryLayers.addImageryProvider(tdtLayer);
}

export function getViewerMap() {
  return viewer;
}

// ==================== 使用 Entity API 添加点线面 ====================
// 1. 使用 Entity 添加点
// 红色圆点 - 北京  蓝色原点 - 上海
export function addEntityPoint() {
  let coordinateData = [
    {
      lon: 116.3974,
      lat: 39.9093,
      id: "entity-point-beijing",
      name: "北京 - Entity点",
      // color: Cesium.Color(255,0,0)
      color: Cesium.Color.fromCssColorString("#f00"),
    },
    {
      lon: 121.4737,
      lat: 31.2304,
      id: "entity-point-shanghai",
      name: "上海 - Entity点",
      color: Cesium.Color.fromCssColorString("#00f"),
    },
  ];
  for (let index = 0; index < coordinateData.length; index++) {
    const element = coordinateData[index];
    viewer.entities.add({
      id: element.id,
      name: element.name,
      position: Cesium.Cartesian3.fromDegrees(element.lon, element.lat), // 经度，纬度
      point: new Cesium.PointGraphics({
        pixelSize: 15, // 点的像素大小
        color: element.color, // 点的颜色
        outlineColor: Cesium.Color.fromCssColorString("#fff"), // 边框颜色
        outlineWidth: 2, // 边框宽度
        heightReference: 0, // 高度参考（贴地）
      }),
    });
  }
}

// 2. 使用 Entity 添加线
export function addEntityLine() {
  // 红色线条 - 连接北京和上海
  viewer.entities.add({
    id: "entity-line-beijing-shanghai",
    name: "北京-上海连线 - Entity线",
    polyline: new Cesium.PolylineGraphics({
      positions: [
        // Cesium.Cartesian3.fromDegreesArray([data.longitude, data.latitude])
        Cesium.Cartesian3.fromDegrees(116.3974, 39.9093), // 北京
        Cesium.Cartesian3.fromDegrees(121.4737, 31.2304), // 上海
        // Cesium.Cartesian3.fromDegrees(110, 35),
        // Cesium.Cartesian3.fromDegrees(115, 35),
        // Cesium.Cartesian3.fromDegrees(115, 40),
        // Cesium.Cartesian3.fromDegrees(120, 40),
        // Cesium.Cartesian3.fromDegrees(120, 35)
      ],
      width: 5, // 线条宽度
      clampToGround: true, // 贴地显示
      material: Cesium.Color.fromCssColorString("#0f0"), // 线条材质颜色
    }),
  });
}

// 3. 使用 Entity 添加面
// 黄色半透明多边形
export function addEntityPolygonDiaphaneity() {
  viewer.entities.add({
    id: "entity-polygon-blue",
    name: "黄色多边形 - Entity面",
    polygon: new Cesium.PolygonGraphics({
      hierarchy: [
        Cesium.Cartesian3.fromDegrees(105, 30),
        Cesium.Cartesian3.fromDegrees(110, 30),
        Cesium.Cartesian3.fromDegrees(110, 35),
        Cesium.Cartesian3.fromDegrees(105, 35),
      ],
      material: Cesium.Color.YELLOW.withAlpha(0.3), // 半透明黄色
      outline: true, // 显示边框
      outlineColor: Cesium.Color.fromCssColorString("#f00"), // 边框颜色
      extrudedHeight: 50000, // 拉伸高度（米）
    }),
  });
}
// 红色多边形（带洞）
export function addEntityPolygon() {
  viewer.entities.add({
    id: "entity-polygon-with-hole",
    name: "带洞多边形 - Entity面",
    polygon: new Cesium.PolygonGraphics({
      hierarchy: {
        positions: [
          // 外边界
          Cesium.Cartesian3.fromDegrees(125, 30),
          Cesium.Cartesian3.fromDegrees(135, 30),
          Cesium.Cartesian3.fromDegrees(135, 40),
          Cesium.Cartesian3.fromDegrees(125, 40),
        ],
        holes: [
          // 内部洞
          {
            positions: [
              Cesium.Cartesian3.fromDegrees(128, 33),
              Cesium.Cartesian3.fromDegrees(132, 33),
              Cesium.Cartesian3.fromDegrees(132, 37),
              Cesium.Cartesian3.fromDegrees(128, 37),
            ],
          },
        ],
      },
      material: Cesium.Color.RED.withAlpha(0.6),
      outline: true,
      outlineColor: Cesium.Color.RED,
    }),
  });
}

// ==================== 使用 Primitive API 添加点线面 ====================
// 4. 使用 Primitive 添加点
export function addPrimitivePoint() {
  // 创建点集合 - 使用 PointPrimitiveCollection
  const pointCollection = new Cesium.PointPrimitiveCollection();
  // 添加黄色点
  pointCollection.add({
    position: Cesium.Cartesian3.fromDegrees(100, 25), // 广州附近
    color: Cesium.Color.YELLOW,
    pixelSize: 20,
    outlineColor: Cesium.Color.BLACK,
    outlineWidth: 2,
    id: "primitive-point-1",
  });

  // 添加紫色点
  pointCollection.add({
    position: Cesium.Cartesian3.fromDegrees(103, 28), // 成都附近
    color: Cesium.Color.PURPLE,
    pixelSize: 25,
    outlineColor: Cesium.Color.WHITE,
    outlineWidth: 3,
    id: "primitive-point-2",
  });

  // 将点集合添加到场景
  viewer.scene.primitives.add(pointCollection);
}

// 5. 使用 Primitive 添加线
export function addPrimitiveLine() {
  // 创建线几何实例
  const polylineInstances = [
    new Cesium.GeometryInstance({
      geometry: new Cesium.PolylineGeometry({
        positions: [
          Cesium.Cartesian3.fromDegrees(90, 20),
          Cesium.Cartesian3.fromDegrees(95, 25),
          Cesium.Cartesian3.fromDegrees(100, 20),
          Cesium.Cartesian3.fromDegrees(110, 35),
          Cesium.Cartesian3.fromDegrees(115, 35),
          Cesium.Cartesian3.fromDegrees(115, 40),
          Cesium.Cartesian3.fromDegrees(120, 40),
          Cesium.Cartesian3.fromDegrees(120, 35),
        ],
        width: 10.0,
      }),
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          Cesium.Color.ORANGE
        ),
      },
      id: "primitive-polyline-1",
    }),
  ];

  // 添加线Primitive到场景
  viewer.scene.primitives.add(
    new Cesium.Primitive({
      geometryInstances: polylineInstances,
      appearance: new Cesium.PolylineMaterialAppearance({
        material: Cesium.Material.fromType("Color", {
          color: Cesium.Color.ORANGE,
        }),
      }),
    })
  );
}

// 6. 使用 Primitive 添加面
export function addPrimitivePolygon() {
  // 创建多边形几何实例
  const polygonInstances = [
    new Cesium.GeometryInstance({
      geometry: new Cesium.PolygonGeometry({
        polygonHierarchy: {
          positions: [
            Cesium.Cartesian3.fromDegrees(85, 15),
            Cesium.Cartesian3.fromDegrees(95, 15),
            Cesium.Cartesian3.fromDegrees(95, 25),
            Cesium.Cartesian3.fromDegrees(85, 25),
          ],
        },
        extrudedHeight: 100000, // 拉伸高度
      }),
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          Cesium.Color.CYAN.withAlpha(0.7)
        ),
      },
      id: "primitive-polygon-1",
    }),
    new Cesium.GeometryInstance({
      geometry: new Cesium.PolygonGeometry({
        polygonHierarchy: {
          positions: [
            Cesium.Cartesian3.fromDegrees(75, 35),
            Cesium.Cartesian3.fromDegrees(85, 35),
            Cesium.Cartesian3.fromDegrees(80, 45),
          ],
        },
      }),
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          Cesium.Color.MAGENTA.withAlpha(0.8)
        ),
      },
      id: "primitive-polygon-2",
    }),
  ];

  // 添加面Primitive到场景
  viewer.scene.primitives.add(
    new Cesium.Primitive({
      geometryInstances: polygonInstances,
      appearance: new Cesium.EllipsoidSurfaceAppearance({
        material: Cesium.Material.fromType("Color", {
          color: Cesium.Color.CYAN.withAlpha(0.5),
        }),
        translucent: true,
      }),
    })
  );

  // 设置相机视角，显示所有添加的元素
  // 计算所有图形的边界，设置最佳观察位置
  // 图形分布范围：经度 75-135，纬度 15-45
  /*viewer.camera.setView({
    destination: Cartesian3.fromDegrees(105, 30, 3000000), // 经度，纬度，高度（米）
    orientation: {
      heading: 0.0, // 方向角（正北方向）
      pitch: -0.7,  // 俯仰角（向下看）
      roll: 0.0     // 翻滚角
    }
  });*/
  // 自动计算最佳视角
  // viewer.flyTo(viewer.entities);

  onLeftClickEvent();
}

// ==================== 辅助功能 ====================
// 鼠标左键点击事件 - 用于查看点击的实体信息
function onLeftClickEvent() {
  viewer.cesiumWidget.screenSpaceEventHandler.setInputAction(
    function onLeftClick(event) {
      const pickedObject = viewer.scene.pick(event.position);
      if (pickedObject && pickedObject.id) {
        console.log("点击的实体:", pickedObject.id);
        // 如果是Entity，可以获取更多信息
        if (pickedObject.id.name) {
          console.log("实体名称:", pickedObject.id.name);
        }
      }
    },
    2
  ); // 2 代表鼠标左键点击事件
}

// 添加glb模型
export function addGLB() {
  // 基本用法
  const entity = viewer.entities.add({
    name: "GLB模型示例",
    position: Cesium.Cartesian3.fromDegrees(116.3974, 39.9093),
    // 设置模型初始朝向（这里设置为朝北，即heading=0）
    orientation: Cesium.Transforms.headingPitchRollQuaternion(
      Cesium.Cartesian3.fromDegrees(
        coordinateData[0].lon,
        coordinateData[0].lat
      ),
      new Cesium.HeadingPitchRoll(
        Cesium.Math.toRadians(270), // 朝向（heading）：0表示朝北，正数为顺时针旋转（东：90，南：180，西：270）
        0, // 俯仰角（pitch）：0表示水平
        0 // 横滚角（roll）：0表示不倾斜
      )
    ),
    model: {
      uri: "car.glb",
      scale: 2.0,
      minimumPixelSize: 1228,
      maximumScale: 20000,
      incrementallyLoadTextures: true,
      clampAnimations: true,
      shadows: Cesium.ShadowMode.ENABLED,
    },
  });

  // 自动定位到模型
  // viewer.trackedEntity = entity;
}

// 添加图片标记点
export function addImgPoint() {
  // 添加一个Billboard作为标记
  viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(110, 30.0), // 经纬度坐标
    billboard: new Cesium.BillboardGraphics({
      image: "111.png", // 图片路径
      width: 50, // 图片宽度
      height: 50, // 图片高度
    }),
  });
}

let coordinateData = [
  {
    lon: 110,
    lat: 30,
    id: "0",
    name: "traject0",
  },
  {
    lon: 110.2,
    lat: 30,
    id: "1",
    name: "traject1",
  },
  {
    lon: 110.4,
    lat: 30.2,
    id: "2",
    name: "traject2",
  },
  {
    lon: 110.8,
    lat: 30.4,
    id: "3",
    name: "traject3",
  },
  {
    lon: 111,
    lat: 31,
    id: "4",
    name: "traject4",
  },
  {
    lon: 111.3,
    lat: 31,
    id: "5",
    name: "traject5",
  },
  {
    lon: 111.6,
    lat: 31,
    id: "6",
    name: "traject6",
  },
  {
    lon: 111.9,
    lat: 31,
    id: "7",
    name: "traject7",
  },
  {
    lon: 112,
    lat: 31,
    id: "8",
    name: "traject8",
  },
  {
    lon: 112.3,
    lat: 31,
    id: "9",
    name: "traject9",
  },
  {
    lon: 112.5,
    lat: 31,
    id: "10",
    name: "traject10",
  },
  {
    lon: 112.8,
    lat: 31,
    id: "11",
    name: "traject11",
  },
  {
    lon: 113,
    lat: 31,
    id: "12",
    name: "traject12",
  },
  {
    lon: 114,
    lat: 31,
    id: "13",
    name: "traject13",
  },
  {
    lon: 115.3,
    lat: 32,
    id: "14",
    name: "traject14",
  },
  {
    lon: 115.5,
    lat: 32,
    id: "15",
    name: "traject15",
  },
  {
    lon: 115.8,
    lat: 31.8,
    id: "16",
    name: "traject16",
  },
  {
    lon: 116,
    lat: 31.4,
    id: "17",
    name: "traject17",
  },
  {
    lon: 116.2,
    lat: 31.1,
    id: "18",
    name: "traject18",
  },
  {
    lon: 116.5,
    lat: 30.5,
    id: "19",
    name: "traject19",
  },
  {
    lon: 115,
    lat: 30.2,
    id: "20",
    name: "traject20",
  },
  {
    lon: 114,
    lat: 29.8,
    id: "21",
    name: "traject21",
  },
  {
    lon: 113,
    lat: 29.6,
    id: "22",
    name: "traject22",
  },
  {
    lon: 112,
    lat: 29.4,
    id: "23",
    name: "traject23",
  },
  {
    lon: 111,
    lat: 30.5,
    id: "24",
    name: "traject24",
  },
  {
    lon: 110,
    lat: 30.4,
    id: "25",
    name: "traject25",
  },
  {
    lon: 109,
    lat: 30.6,
    id: "26",
    name: "traject26",
  },
  {
    lon: 108,
    lat: 36,
    id: "27",
    name: "traject27",
  },
];
// 添加使用glb模型进行实时轨迹
export function addGlbTrajectory() {
  // 先添加初始线条
  let arr = [coordinateData[0].lon, coordinateData[0].lat];
  let glbEntity = viewer.entities.add({
    name: "GLB模型示例",
    position: Cesium.Cartesian3.fromDegrees(
      coordinateData[0].lon,
      coordinateData[0].lat
    ),
    // 设置模型初始朝向（这里设置为朝北，即heading=0）
    orientation: Cesium.Transforms.headingPitchRollQuaternion(
      Cesium.Cartesian3.fromDegrees(
        coordinateData[0].lon,
        coordinateData[0].lat
      ),
      new Cesium.HeadingPitchRoll(
        Cesium.Math.toRadians(270), // 朝向（heading）：0表示朝北，正数为顺时针旋转（东：90，南：180，西：270）
        0, // 俯仰角（pitch）：0表示水平
        0 // 横滚角（roll）：0表示不倾斜
      )
    ),
    model: {
      uri: "car.glb",
      scale: 2.0,
      minimumPixelSize: 1228,
      maximumScale: 20000,
      incrementallyLoadTextures: true,
      clampAnimations: true,
      shadows: Cesium.ShadowMode.ENABLED,
    },
  });
  // viewer.trackedEntity = glbEntity;
  let i = 0;
  interval = setInterval(() => {
    // 当数组下标还有数据时
    if (coordinateData[i + 1]) {
      arr.push(coordinateData[i + 1].lon, coordinateData[i + 1].lat);

      // 获取当前点和下一点的坐标
      const currentPos = Cesium.Cartesian3.fromDegrees(
        coordinateData[i].lon,
        coordinateData[i].lat
      );
      const nextPos = Cesium.Cartesian3.fromDegrees(
        coordinateData[i + 1].lon,
        coordinateData[i + 1].lat
      );
      // 更新位置
      glbEntity.position = nextPos;
      // 计算朝向（从当前点指向下一点的方向）
      const heading = -(computeHeading(currentPos, nextPos));

      // 更新朝向
      glbEntity.orientation = Cesium.Transforms.headingPitchRollQuaternion(
        nextPos,
        new Cesium.HeadingPitchRoll(heading, 0, 0)
      );
      // 更新现有模型的位置，而不是创建新模型
      // glbEntity.position = Cesium.Cartesian3.fromDegrees(
      //   coordinateData[i + 1].lon,
      //   coordinateData[i + 1].lat
      // );
      // 轨迹
      viewer.entities.add({
        id: coordinateData[i + 1].id,
        name: coordinateData[i + 1].name,
        polyline: new Cesium.PolylineGraphics({
          positions: Cesium.Cartesian3.fromDegreesArray(arr),
          width: 5, // 线条宽度
          clampToGround: true, // 贴地显示
          material: Cesium.Color.fromCssColorString("#0f0"), // 线条材质颜色
        }),
      });
      i++;
    } else {
      // 已全部获取
      clearInterval(interval);
      interval = null;
    }
  }, 3000);
}

// 计算两点之间的朝向角（弧度）
function computeHeading(start, end) {
  const direction = Cesium.Cartesian3.subtract(
    end,
    start,
    new Cesium.Cartesian3()
  );
  const up = Cesium.Cartesian3.normalize(start, new Cesium.Cartesian3());

  // 计算东方向（垂直于向上方向和北方向）
  const east = Cesium.Cartesian3.cross(
    new Cesium.Cartesian3(0, 0, 1),
    up,
    new Cesium.Cartesian3()
  );
  Cesium.Cartesian3.normalize(east, east);

  // 计算北方向（垂直于东方向和向上方向）
  const north = Cesium.Cartesian3.cross(up, east, new Cesium.Cartesian3());

  // 计算方向向量在水平面（东-北平面）上的投影
  const horizontalDirection = new Cesium.Cartesian3();
  Cesium.Cartesian3.subtract(
    direction,
    Cesium.Cartesian3.multiplyByScalar(
      up,
      Cesium.Cartesian3.dot(direction, up),
      new Cesium.Cartesian3()
    ),
    horizontalDirection
  );
  Cesium.Cartesian3.normalize(horizontalDirection, horizontalDirection);

  // 计算朝向角（从北方向顺时针旋转的角度）
  const dot = Cesium.Cartesian3.dot(north, horizontalDirection);
  const cross = Cesium.Cartesian3.dot(east, horizontalDirection);
  return Math.atan2(cross, dot);
}

// 使用图片进行实时轨迹
export function addImgTrajectory() {
  // 先添加初始线条
  let arr = [coordinateData[0].lon, coordinateData[0].lat];

  // 添加一个Billboard作为标记
  let billboards  = new Cesium.BillboardGraphics({
      image: "111.png", // 图片路径
      width: 50, // 图片宽度
      height: 50, // 图片高度
      rotation: 0
    })
  let glbEntity = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(110, 30.0), // 经纬度坐标
    billboard: billboards
  });

  let i = 0;
  interval = setInterval(() => {
    // 当数组下标还有数据时
    if (coordinateData[i + 1]) {
      arr.push(coordinateData[i + 1].lon, coordinateData[i + 1].lat);

      // 更改图片位置
      // 更新现有模型的位置，而不是创建新模型
      glbEntity.position = Cesium.Cartesian3.fromDegrees(
        coordinateData[i + 1].lon,
        coordinateData[i + 1].lat
      );

      let arc = 0;
      if (
        (coordinateData[i + 1].lon - coordinateData[i].lon >= 0 &&
          coordinateData[i + 1].lat - coordinateData[i].lat >= 0) ||
        (coordinateData[i + 1].lon - coordinateData[i].lon < 0 &&
          coordinateData[i + 1].lat - coordinateData[i].lat > 0)
      ) {
        arc = Math.atan(
          (coordinateData[i + 1].lon - coordinateData[i].lon) /
            (coordinateData[i + 1].lat - coordinateData[i].lat)
        );
      } else if (
        (coordinateData[i + 1].lon - coordinateData[i].lon > 0 &&
          coordinateData[i + 1].lat - coordinateData[i].lat < 0) ||
        (coordinateData[i + 1].lon - coordinateData[i].lon < 0 &&
          coordinateData[i + 1].lat - coordinateData[i].lat < 0)
      ) {
        arc =
          Math.PI +
          Math.atan(
            (coordinateData[i + 1].lon - coordinateData[i].lon) /
              (coordinateData[i + 1].lat - coordinateData[i].lat)
          );
      }
      // 更新图片朝向
      glbEntity.billboard.rotation._value = -(arc)

      // 轨迹
      viewer.entities.add({
        id: coordinateData[i + 1].id,
        name: coordinateData[i + 1].name,
        polyline: new Cesium.PolylineGraphics({
          positions: Cesium.Cartesian3.fromDegreesArray(arr),
          width: 5, // 线条宽度
          clampToGround: true, // 贴地显示
          material: Cesium.Color.fromCssColorString("#0f0"), // 线条材质颜色
        }),
      });
      i++;
    } else {
      // 已全部获取
      clearInterval(interval);
      interval = null;
    }
  }, 1000);
}

export function clearIntervalEvent() {
  if (interval) {
    clearInterval(interval);
    interval = null;
  }
}
